package com.compty.paint.web.member;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.compty.core.framework.util.DateUtil;
import com.compty.core.framework.util.FileUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.page.Page;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.AuditState;
import com.compty.paint.domain.Bid;
import com.compty.paint.domain.CatalogType;
import com.compty.paint.domain.Goods;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.domain.LogInfo;
import com.compty.paint.domain.PaintType;
import com.compty.paint.domain.Painter;
import com.compty.paint.domain.Painting;
import com.compty.paint.domain.SharpInfo;
import com.compty.paint.domain.UploadState;
import com.compty.paint.domain.support.LogTypeEnum;
import com.compty.paint.exception.OrderExistException;
import com.compty.paint.manager.AuditStateManager;
import com.compty.paint.manager.BidManager;
import com.compty.paint.manager.CatalogTypeManager;
import com.compty.paint.manager.GoodsManager;
import com.compty.paint.manager.ImageInfoManager;
import com.compty.paint.manager.LogInfoManager;
import com.compty.paint.manager.PaintTypeManager;
import com.compty.paint.manager.PainterManager;
import com.compty.paint.manager.PaintingManager;
import com.compty.paint.manager.SharpInfoManager;
import com.compty.paint.manager.UploadStateManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;
import com.compty.security.manager.UserManager;

/**
 * @Todo:作品
 * @CreateTime:2011-6-9 上午10:31:12
 */
public class PaintingAction extends BaseAction<Painting> {

	private static final long serialVersionUID = -7384403665258646630L;
	private static Log logger = LogFactory.getLog(PaintingAction.class);

	private LogInfoManager logInfoManager;
	private CatalogTypeManager catalogTypeManager;
	private SharpInfoManager sharpInfoManager;
	private PaintingManager paintingManager;
	private PainterManager painterManager;
	private AuditStateManager auditStateManager;
	private UploadStateManager uploadStateManager;
	private PaintTypeManager paintTypeManager;
	private UserManager userManager;
	private ImageInfoManager imageInfoManager;
	private GoodsManager goodsManager;
	private BidManager bidManager;

	// ====================================================
	private List<CatalogType> catalogTypeList; //大类集合
	private List<SharpInfo> sharpInfoList;//形状集合
	private List<PaintType> paintTypeList;//画种集合
	private Painting painting;
	private Painter p;  //为艺术家添加作品时，显示艺术家信息
	
	private Date startDate;
	private Date endDate;
	private Long catalogId;
	private String ajaxData;
	private String operateStr; // 1表示隐藏,2表示删除
	private String auditStateType; //查询审核类型
	
    private File myFile;
    private String fileName;//图片原始名字

	/**
	 * 添加作品(按作品发布)
	 */
	public String addPrepare() {
		this.painting = null;
		this.p = null;
		
		User userInfo = (User) session.getAttribute(Constants.Userinfo);
		userInfo = userManager.get(userInfo.getId());
		
		this.catalogTypeList = catalogTypeManager.getAll();
		this.sharpInfoList = sharpInfoManager.getAll();
		
		/**************** 已有艺术家列表    begin ****************************/
		List<Painter> painterList = painterManager.findByEntryPerson(userInfo.getId(),userInfo.getAdministratorFlag()) ;
		request.setAttribute("painterList", painterList);
		/**************** 已有艺术家列表   end  ****************************/

		return SUCCESS;
	}

	/**
	 * 从艺术家添加作品(按艺术家发布时添加作品)
	 */
	public String addPrepareByPainter() {
		this.painting = null;
		this.p = null;
		
		String painter_Id = request.getParameter("painter_Id");
		Long painterId = Long.parseLong(painter_Id);
		this.p = painterManager.get(painterId);
		
		Long catalogId = p.getCatalogType().getId();
		CatalogType catalogType = catalogTypeManager.get(catalogId);
		this.paintTypeList = paintTypeManager.findBy("catalogType", catalogType);

		this.sharpInfoList = sharpInfoManager.getAll();

		return SUCCESS;
	}
	
	/**
	 * 从名家添加作品(按艺术家发布时添加作品)
	 */
	public String addPrepareByPainterStar(){
		this.painting = null;
		this.p = null;

		String painter_Id = request.getParameter("painter_Id");
		Long painterId = Long.parseLong(painter_Id);
		this.p = painterManager.get(painterId);

		this.sharpInfoList = sharpInfoManager.getAll();

		return SUCCESS;
	}

	/**
	 * 保存作品
	 */
	public String save() throws Exception {

		if (painting != null) {
			
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			userInfo = userManager.get(userInfo.getId());
			painting.setEntryPerson(userInfo);
			painting.setModifyTime(Calendar.getInstance().getTime());
			painting.setUploadTime(Calendar.getInstance().getTime());
			painting.setProvider(userInfo.getUsername());
			String mktprice = request.getParameter("mktprice");
			
			if( painting.getPainter() != null && painting.getPainter().getId() == null){
				painting.setPainter(null);
			}

			/******************  上传状态及审核状态  begin  ************************/
			UploadState uploadState = uploadStateManager.findUniqueBy("english_name",Constants.Upload_State_Init);
			painting.setUploadState(uploadState);

			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				painting.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				painting.setAuditState(auditState);
			}
			/******************  上传状态及审核状态 end ************************/
			
			/******************  保存证书图片  begin  ************************/
				saveZhengshuPic(painting);
			/******************  保存证书图片  end  ************************/
				
			dealOtherPicturesOfPainting(painting);
			paintingManager.save(painting);//保存作品
			generateImageOfPaintingAfterSaved(painting);//第一次生成作品图片
			
			/******************  上拍处理  begin  ************************/
			String onSaleFlag = painting.getOnSaleFlag();
			if( "1".equals(onSaleFlag)){
				String beginPrice = request.getParameter("beginPrice");
				String beginTime = request.getParameter("beginTime");
				String endTime = request.getParameter("endTime");
				
				if( beginPrice != null && !"".equals(beginPrice)){
					painting.setBidPrice(Float.valueOf(beginPrice));
				}
				Goods goods = buildGoods(painting,mktprice,"bid");
				
				Long paintingId = painting.getId();
				goods.setPainting_id(paintingId);
				goodsManager.save(goods);
				
				Bid bid = buildBid(userInfo,goods,beginPrice,beginTime,endTime);
				if( painting.getPainter() != null){
					bid.setPainter_Id(painting.getPainter().getId());
				}
				
				bidManager.save(bid);
			}
			/******************  上拍处理  end  ************************/
			else if("2".equals(onSaleFlag)){
				if( painting.getPrice() != null && painting.getPrice() > 0){
					Goods goods = buildGoods(painting,mktprice,null);
					Long paintingId = painting.getId();
					goods.setPainting_id(paintingId);
					goodsManager.save(goods);
				}
			}

			LogInfo logInfo = buildLogInfo(LogTypeEnum.addPainting, "保存作品"+painting.getId()+","+painting.getTitle()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		request.setAttribute("ajaxData", "0000");
		request.setAttribute("returnMsg", "上传作品成功");
		
		addPaintingToSession(painting);//将新添作品加入session

		return SUCCESS;
	}
	
	/**
	 * 保存作品(添加艺术家的作品)
	 * @throws IOException
	 */
	public String saveByPainter() throws Exception {

		if (painting != null) {

			String mktprice = request.getParameter("mktprice");
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			painting.setEntryPerson(userInfo);
			painting.setModifyTime(Calendar.getInstance().getTime());
			painting.setUploadTime(Calendar.getInstance().getTime());
			painting.setProvider(userInfo.getUsername());

			UploadState uploadState = uploadStateManager.findUniqueBy("english_name",Constants.Upload_State_Init);
			painting.setUploadState(uploadState);

			if(Constants.Auto_Audit){
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Pass);
				painting.setAuditState(auditState);
			}else{
				AuditState auditState = auditStateManager.findUniqueBy("english_name",Constants.Audit_State_Init);
				painting.setAuditState(auditState);
			}
			
			/******************  保存证书图片  begin  ************************/
				saveZhengshuPic(painting);
			/******************  保存证书图片  end  ************************/
			
			dealOtherPicturesOfPainting(painting);
			paintingManager.save(painting);
			generateImageOfPaintingAfterSaved(painting);//第一次生成作品图片
			
			/******************  上拍处理  begin  ************************/
			String onSaleFlag = painting.getOnSaleFlag();
			if( "1".equals(onSaleFlag)){
				String beginPrice = request.getParameter("beginPrice");
				String beginTime = request.getParameter("beginTime");
				String endTime = request.getParameter("endTime");
				
				if( beginPrice != null && !"".equals(beginPrice)){
					painting.setBidPrice(Float.valueOf(beginPrice));
				}
				Goods goods = buildGoods(painting,mktprice,"bid");
				
				Long paintingId = painting.getId();
				goods.setPainting_id(paintingId);
				goodsManager.save(goods);
				
				Bid bid = buildBid(userInfo,goods,beginPrice,beginTime,endTime);
				bid.setPainter_Id(painting.getPainter().getId());
				bidManager.save(bid);
			}
			/******************  上拍处理  end  ************************/
			else if("2".equals(onSaleFlag)){
				if( painting.getPrice() != null && painting.getPrice() > 0){
					Goods goods = buildGoods(painting,mktprice,null);
					Long paintingId = painting.getId();
					goods.setPainting_id(paintingId);
					goodsManager.save(goods);
				}
			}

			LogInfo logInfo = buildLogInfo(LogTypeEnum.addPainting, "保存作品"+painting.getId()+","+painting.getTitle()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		request.setAttribute("ajaxData", "0000");
		request.setAttribute("returnMsg", "上传作品成功");
		
		addPaintingToSession(painting);//将新添作品加入session

		return SUCCESS;
	}

	/**
	 *@Todo:列出作品
	 *@CreateTime:2011-6-9 上午09:32:14
	 */
	public String listPainting() {

		Criteria criteria;
		if (sort != null) {
			boolean isAsc = dir.equalsIgnoreCase("asc");
			criteria = paintingManager.createCriteria(sort, isAsc);
		} else {
			criteria = paintingManager.createCriteria();
		}

		criteria.addOrder(Order.desc("id"));
		
		User userInfo = (User) session.getAttribute(Constants.Userinfo);
		if( userInfo!= null && "0".equals(userInfo.getAdministratorFlag())){
			 criteria = criteria.add(Restrictions.eq("entryPerson", userInfo));
		}

		if (startDate != null) {
			criteria = criteria.add(Restrictions.ge("uploadTime", startDate));
		}

		if (endDate != null) {
			criteria = criteria.add(Restrictions.lt("uploadTime", endDate));
		}
		
		if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
	            criteria = criteria.add(Restrictions.like(filterTxt,"%" + filterValue + "%"));
	    }

		this.page = paintingManager.pagedQuery(criteria, curPage, pageSize);

		return SUCCESS;
	}
	
	/**
	 * 列出最新(本次登录)添加的所有作品
	 *@CreateTime:2011-7-22 上午09:06:27
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String listNewestPainting() {

		List<Long> paintingIdListInSession = (List<Long>) session.getAttribute(Constants.paintingIdListInSession);
		if( paintingIdListInSession != null ){
			
			int size = paintingIdListInSession.size();
			int begin = (curPage-1)*8;
			
			List<Painting> result = new ArrayList<Painting>();
			for (int i = begin; i < size; i++) {
				Long id = paintingIdListInSession.get(i);
				Painting p = paintingManager.get(id);
				result.add(p);
			}
			
			this.page = new Page();
			page.setResult(result);
			page.setPageNo(curPage);
			page.setPageSize(8);
			page.setTotalCount(size);
		}

		return "newestPainting";
	}
	
	/**
	 * 列出画家所拥有作品
	 * @return
	 */
	public String listPaintingByPainter() {
		
		String painter_id_str = request.getParameter("painter_Id");
		Long painter_Id = Long.parseLong(painter_id_str);

		Criteria criteria;
		if (sort != null) {
			boolean isAsc = dir.equalsIgnoreCase("asc");
			criteria = paintingManager.createCriteria(sort, isAsc);
		} else {
			criteria = paintingManager.createCriteria();
		}
		
		criteria.addOrder(Order.desc("id"));

		User userInfo = (User) session.getAttribute(Constants.Userinfo);
		if( userInfo!= null && "0".equals(userInfo.getAdministratorFlag())){
			 criteria = criteria.add(Restrictions.eq("entryPerson", userInfo));
		}
		
		this.p  = painterManager.get(painter_Id);
		criteria.add(Restrictions.eq("painter",p));

		this.page = paintingManager.pagedQuery(criteria, curPage, 8);

		return "listPaintingByPainter";
	}

	/**
	 *@Todo:展现作品详情
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 上午09:46:18
	 */
	public String modifyPrepare() {

		if (painting != null) {
			
			User userInfo = (User) session.getAttribute(Constants.Userinfo);
			userInfo = userManager.get(userInfo.getId());
			
			this.catalogTypeList = catalogTypeManager.getAll();
			this.sharpInfoList = sharpInfoManager.getAll();
			
			/**************** 已有艺术家列表    begin ****************************/
			List<Painter> painterList = painterManager.findByEntryPerson(userInfo.getId(),userInfo.getAdministratorFlag()) ;
			request.setAttribute("painterList", painterList);
			/**************** 已有艺术家列表   end  ****************************/

			Long id = painting.getId();
			this.painting = paintingManager.get(id);
			
			Bid bid  = bidManager.findByPaintingId(id);
			if( bid == null){
				request.setAttribute("onbid_flag", "0");
			}else{
				Integer status = bid.getStatus();
				if( status != null &&  1 ==  status ){
					request.setAttribute("onbid_flag", "1");
				}else{
					request.setAttribute("onbid_flag", "0");
				}
			}
			request.setAttribute("bid", bid);
			
			Goods goods = goodsManager.findByPaintingId(id);
			if( goods != null){
				request.setAttribute("goods", goods);
			}
			
			Painter painter = painting.getPainter();
			if( painter != null && "2".equals(painter.getType())){ // 表示是名家作品
				return "modify_paintingOfPainterStar";
			}
		}
		return SUCCESS;
	}

	/**
	 * 修改画品信息
	 * @author:朱庆辉
	 *@CreateTime:2011-6-9 上午10:19:01
	 */
	public String modify() throws Exception{
		
		User userInfo = (User) session.getAttribute(Constants.Userinfo);
		
		String mktprice = request.getParameter("mktprice");
		String beginPrice = request.getParameter("beginPrice");
		String beginTime = request.getParameter("beginTime");
		String endTime = request.getParameter("endTime");

		if (painting != null) {
			
			if( painting.getPainter() != null && painting.getPainter().getId() == null){
				painting.setPainter(null);
			}
			
			Date lastModifyTime = Calendar.getInstance().getTime();
			Painting p = paintingManager.get(painting.getId());
			p.setModifyTime(lastModifyTime);

			UploadState uploadState = uploadStateManager.findUniqueBy("english_name",Constants.Upload_State_Init);
			p.setUploadState(uploadState);
			
			p.setTitle(painting.getTitle());
			p.setCaiZhi(painting.getCaiZhi());
			p.setCatalogType(painting.getCatalogType());
			p.setHasBorder(painting.isHasBorder());
			p.setImageInfo(painting.getImageInfo());
			p.setPainter(painting.getPainter());
			p.setPaintType(painting.getPaintType());
			p.setPrice(painting.getPrice());
			p.setBidPrice(painting.getBidPrice());
			p.setHight(painting.getHight());
			p.setWidth(painting.getWidth());
			p.setAltitude(painting.getAltitude());
			p.setSharpInfo(painting.getSharpInfo());
			p.setQqxl(painting.getQqxl());
			p.setUnit(painting.getUnit());
			p.setUnit2(painting.getUnit2());
			p.setStore(painting.getStore());
			p.setRemark(painting.getRemark());
			p.setOnSaleFlag(painting.getOnSaleFlag());
			
			/***************** 修改作品形状  begin  *************************/
				SharpInfo sharpInfo = painting.getSharpInfo();
				Long sharpId = sharpInfo.getId();
				ImageInfo imageInfo = painting.getImageInfo();
				imageInfo = imageInfoManager.get(imageInfo.getId());
				imageInfo.setSharpId(sharpId);
				imageInfoManager.save(imageInfo);
			/***************** 修改作品形状  end  *************************/
				
			/******************  保存证书图片  begin  ************************/
				saveZhengshuPic(p);
			/******************  保存证书图片  end  ************************/
			
			String onSaleFlag = painting.getOnSaleFlag();//作品用途
			if("1".equals(onSaleFlag)){//上拍
				p.setProvider(p.getEntryPerson().getUsername());
				
				Long paintingId = p.getId();
				Goods goods = goodsManager.findByPaintingId(paintingId);
				if( goods != null){
					dealGoodsSaleStatus(goods,true,painting,mktprice);
					goods.setLast_modify(lastModifyTime);
					goodsManager.save(goods);
				}else{
					goods = buildGoods(painting,mktprice,"bid");
					goods.setPainting_id(paintingId);
					goodsManager.save(goods);
				}
				
				Bid bid = bidManager.findByPaintingId(paintingId);
				if( painting.getPainter()!= null ){
					bid.setPainter_Id(painting.getPainter().getId());
				}
				if( bid != null){
					bid.setAudit_status(2);
					bid.setBid_status(1);
					bid.setStatus(1);
					bid.setModifyTime(lastModifyTime);
					if( beginPrice != null && !"".equals(beginPrice)){
						bid.setBeginPrice(Double.valueOf(beginPrice));
					}
					bid.setBeginTime(DateUtil.toDate(beginTime,"yyyy-MM-dd HH:mm"));
					bid.setEndTime(DateUtil.toDate(endTime,"yyyy-MM-dd HH:mm"));
					bidManager.save(bid);
				}else{
					bid = buildBid(userInfo,goods,beginPrice,beginTime,endTime);
					bidManager.save(bid);
				}
			}
			else if("2".equals(onSaleFlag)){//上架销售
				Long paintingId = p.getId();
				Goods goods = goodsManager.findByPaintingId(paintingId);
				if( goods != null){
					bidManager.removeByGoodsId(goods.getId());
					dealGoodsSaleStatus(goods,true,painting,mktprice);
					goodsManager.save(goods);
				}else{
					goods = buildGoods(painting,mktprice,"bid");
					goods.setPainting_id(paintingId);
					goodsManager.save(goods);
				}
			}else{
				Long paintingId = p.getId();
				try {
					goodsManager.removeByPaintingId(paintingId);
				} catch (OrderExistException e) {
				}
			}
			
			dealOtherPicturesOfPainting(p);
			paintingManager.save(p);
			generateImageOfPaintingAfterSaved(p);//第一次生成作品图片
			
			LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyPainting, "修改作品"+painting.getTitle()+"基本资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		request.setAttribute("ajaxData", "0000");
		request.setAttribute("returnMsg", "修改作品成功");

		return SUCCESS;
	}


	/**
	 *@Todo:修改作品上传状态
	 *@CreateTime:2011-6-9 上午10:19:17
	 */
	public String changeUploadState() {

		if (painting != null) {
			Long id = painting.getId();
			this.painting = paintingManager.get(id);

			if ("1".equals(operateStr)) {//隐藏
				UploadState uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Hidden);
				painting.setUploadState(uploadState);
				painting.setModifyTime(Calendar.getInstance().getTime());
				paintingManager.save(painting);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyPainting, "修改作品"+painting.getTitle()+"基本资料,operate:隐藏");
				logInfoManager.writeLog(logInfo);
				
			} else if ("2".equals(operateStr)) { //删除
				try {
					paintingManager.deleteById(id);
				} catch (OrderExistException e) {
					String returnMsg  = e.getMsg();
					request.setAttribute("ajaxData", returnMsg);
					return SUCCESS;
				}
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.deletePainting, "删除作品"+painting.getTitle()+"基本资料");
				logInfoManager.writeLog(logInfo);
			}
			else if("3".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Pass);  //审核通过
				painting.setAuditState(auditState);
				painting.setModifyTime(Calendar.getInstance().getTime());
				paintingManager.save(painting);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.audit_pass_painting, "审核通过作品"+painting.getTitle()+"基本资料");
				logInfoManager.writeLog(logInfo);
			}
			else if("4".equals(operateStr)){
				AuditState auditState = auditStateManager.findUniqueBy("english_name", Constants.Audit_State_Overrule);  //审核驳回
				painting.setAuditState(auditState);
				painting.setModifyTime(Calendar.getInstance().getTime());
				paintingManager.save(painting);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.audit_overrule_painting, "审核驳回作品"+painting.getTitle()+"基本资料");
				logInfoManager.writeLog(logInfo);
			}
			else if("5".equals(operateStr)){//显示
				UploadState uploadState = uploadStateManager.findUniqueBy("english_name", Constants.Upload_State_Init);
				painting.setUploadState(uploadState);
				painting.setModifyTime(Calendar.getInstance().getTime());
				paintingManager.save(painting);
				
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyPainting, "修改作品"+painting.getTitle()+"基本资料,operate:显示");
				logInfoManager.writeLog(logInfo);
			}			
			else if("6".equals(operateStr)){//置顶
				painting.setSortFlag(1);
				painting.setOrderNo(0);
				paintingManager.save(painting);
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyPainting, "修改作品"+painting.getTitle()+"基本资料,operate:置顶");
				logInfoManager.writeLog(logInfo);
			}
			else if("7".equals(operateStr)){//取消置顶
				painting.setSortFlag(0);
				painting.setOrderNo(null);
				paintingManager.save(painting);
				LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyPainting, "修改作品"+painting.getTitle()+"基本资料,operate:取消置顶");
				logInfoManager.writeLog(logInfo);
			}
		}
		
		request.setAttribute("ajaxData", "0000");
		
		return SUCCESS;
	}

	/**
	 * 由大类查找小类
	 */
	@SuppressWarnings({ "unchecked" })
	public String findPaintTypeByCatalogId() {

		CatalogType catalogType = catalogTypeManager.get(catalogId);

		this.paintTypeList = paintTypeManager.findBy("catalogType", catalogType);

		List<Map> returnList = new ArrayList<Map>();
		for (PaintType paintType : paintTypeList) {
			Map map = new HashMap();
			map.put("id", paintType.getId());
			map.put("typeName", paintType.getTypeName());
			returnList.add(map);
		}

		this.ajaxData = JSONArray.fromObject(returnList).toString();
		return SUCCESS;
	}
	
	/**
	 * 上传图片 
	 */
	public String uploadImage(){
		
		if ( myFile != null ) {
			long filenameExclude = RandomUtils.nextInt();
			String newImageFileName = filenameExclude + "."+ StringUtil.getExt(fileName) ;
			String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + newImageFileName;
			File imageFile = new File(srcpath);
			FileUtil.copy(myFile, imageFile);
			
			request.setAttribute("ajaxData", "{code:\"0000\",message:\""+newImageFileName+"\"}");
			return "uploadSuccess";
		}
		
		request.setAttribute("ajaxData", "{code:\"0001\",message:\"文件上传失败。\"}");
		return "uploadSuccess";
	}
	
	@SuppressWarnings("unchecked")
	private void addPaintingToSession(Painting painting){
		
		List<Long> paintingIdListInSession = (List<Long>) session.getAttribute(Constants.paintingIdListInSession);
		if(paintingIdListInSession == null){
			paintingIdListInSession = new ArrayList<Long>();
		}
		paintingIdListInSession.add(painting.getId());
		session.setAttribute(Constants.paintingIdListInSession, paintingIdListInSession);
		
	}

	public List<CatalogType> getCatalogTypeList() {
		return catalogTypeList;
	}

	public void setCatalogTypeList(List<CatalogType> catalogTypeList) {
		this.catalogTypeList = catalogTypeList;
	}

	public List<SharpInfo> getSharpInfoList() {
		return sharpInfoList;
	}

	public void setSharpInfoList(List<SharpInfo> sharpInfoList) {
		this.sharpInfoList = sharpInfoList;
	}

	public List<PaintType> getPaintTypeList() {
		return paintTypeList;
	}

	public void setPaintTypeList(List<PaintType> paintTypeList) {
		this.paintTypeList = paintTypeList;
	}

	public Painting getPainting() {
		return painting;
	}

	public void setPainting(Painting painting) {
		this.painting = painting;
	}

	public void setPaintingManager(PaintingManager paintingManager) {
		this.paintingManager = paintingManager;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getOperateStr() {
		return operateStr;
	}

	public void setOperateStr(String operateStr) {
		this.operateStr = operateStr;
	}

	public Long getCatalogId() {
		return catalogId;
	}

	public void setCatalogId(Long catalogId) {
		this.catalogId = catalogId;
	}

	public String getAjaxData() {
		return ajaxData;
	}

	public void setAjaxData(String ajaxData) {
		this.ajaxData = ajaxData;
	}

	public Painter getP() {
		return p;
	}

	public void setP(Painter p) {
		this.p = p;
	}

	public void setCatalogTypeManager(CatalogTypeManager catalogTypeManager) {
		this.catalogTypeManager = catalogTypeManager;
	}

	public void setSharpInfoManager(SharpInfoManager sharpInfoManager) {
		this.sharpInfoManager = sharpInfoManager;
	}

	public void setAuditStateManager(AuditStateManager auditStateManager) {
		this.auditStateManager = auditStateManager;
	}

	public void setUploadStateManager(UploadStateManager uploadStateManager) {
		this.uploadStateManager = uploadStateManager;
	}

	public void setPaintTypeManager(PaintTypeManager paintTypeManager) {
		this.paintTypeManager = paintTypeManager;
	}

	public void setPainterManager(PainterManager painterManager) {
		this.painterManager = painterManager;
	}

	public String getAuditStateType() {
		return auditStateType;
	}

	public void setAuditStateType(String auditStateType) {
		this.auditStateType = auditStateType;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setImageInfoManager(ImageInfoManager imageInfoManager) {
		this.imageInfoManager = imageInfoManager;
	}

	public void setLogInfoManager(LogInfoManager logInfoManager) {
		this.logInfoManager = logInfoManager;
	}
	
	public void setGoodsManager(GoodsManager goodsManager) {
		this.goodsManager = goodsManager;
	}

	/*** 构建商品对象 flag普通商品和拍卖商品标识 ***/
	private Goods buildGoods(Painting painting,String mktprice,String flag){
		
		if(painting == null) return null;
		
		Goods goods = new Goods();
		goods.setName(painting.getTitle());
		if( painting.getPainter() !=  null){
			goods.setPage_title(painting.getPainter().getName() + " " +painting.getTitle());
		}
		goods.setCreate_time(Calendar.getInstance().getTime());
		goods.setLast_modify(Calendar.getInstance().getTime());
		if( painting.getPrice()!= null && !"".equals(painting.getPrice())){
			goods.setPrice(Double.valueOf(painting.getPrice()+""));
			if(mktprice != null && !"".equals(mktprice)){
				goods.setMktprice(Double.valueOf(mktprice));
			}
		}
		
		if("bid".equals(flag)){
			goods.setStore(1);
			goods.setView_count(1);
			goods.setBuy_count(1);
			goods.setDisabled(0);
		}else{
			goods.setStore(painting.getStore());
			goods.setView_count(painting.getStore());
			goods.setBuy_count(painting.getStore());
			goods.setDisabled(1);
		}
		
		String sn = getGoodsSN(painting,flag);
		goods.setSn(sn);
		
		goods.setMarket_enable(1);
		goods.setUnit(painting.getUnit());
		goods.setDisabled(1);
		goods.setGoods_type("normal");
		
		return goods;
	}
	
	/************* 得到商品编号  ****************/
	private String getGoodsSN(Painting painting,String flag) {
		Long pId = painting.getId();
		String sn  = "";
		if("bid".equals(flag)){
			sn = "KGPM"+pId;
		}else{
			CatalogType catalogType = painting.getCatalogType();
			if(catalogType.getId() == 3){
				sn = "KGCY"+pId;
			}else{
				sn = "KGSH"+pId;
			}
		}
		return sn;
	}

	/*** 构建拍品对象 ***/
	private Bid buildBid(User userInfo, Goods goods,String beginPrice, String beginTime,String endTime) {
		Bid bid  = new Bid();
		
		bid.setEntryPerson(userInfo);
		bid.setUploadTime(Calendar.getInstance().getTime());
		bid.setModifyTime(Calendar.getInstance().getTime());
		
		bid.setAudit_status(2);
		bid.setBid_status(1);
		bid.setStatus(1);
		
		bid.setTitle(goods.getName());
		bid.setPaintingTitle(goods.getName());
		bid.setGoods_id(goods.getId());
		
		if( beginPrice != null && !"".equals(beginPrice)){
			bid.setBeginPrice(Double.valueOf(beginPrice));
		}
		bid.setBeginTime(DateUtil.toDate(beginTime,"yyyy-MM-dd HH:mm"));
		bid.setEndTime(DateUtil.toDate(endTime,"yyyy-MM-dd HH:mm"));
		
		return bid;
	}
	
	/**
	 * 商品是否销售
	 * @param goods 商品
	 * @param saleFlag 销售标志 true:销售 false:不销售
	 */
	private void dealGoodsSaleStatus(Goods goods, boolean saleFlag,Painting painting,String mktprice) {
		goods.setName(painting.getTitle());
		if( painting.getPainter() !=  null){
			goods.setPage_title(painting.getPainter().getName() + " " +painting.getTitle());
		}
		
		String unit = painting.getUnit();
		Float price = painting.getPrice();
		Integer st = painting.getStore();
		if(saleFlag){
			goods.setDisabled(1);
		}else{
			goods.setDisabled(0);
		}
		goods.setStore(st);
		goods.setView_count(st);
		goods.setBuy_count(st);
		if( price != null ){
			goods.setPrice(Double.valueOf(price+""));
		}
		if( mktprice != null && !"".equals(mktprice)){
			goods.setMktprice(Double.valueOf(mktprice));
		}else{
			goods.setMktprice(null);
		}
		if(null == unit || "".equals(unit)){
			goods.setUnit("件");
		}else{
			goods.setUnit(unit);
		}
	}
	
	/********** 保存证书图片  *****************/
	private void saveZhengshuPic(Painting painting){
		if( myFile != null){
			String imageFileName = getRandomImageFileName() + "."+ StringUtil.getExt(fileName) ;
			String srcpath = getImageUploadPath()+ CommonsUtil.getPathSymbol() + imageFileName;
			File imageFile = new File(srcpath);
			FileUtil.copy(myFile, imageFile);
			
			ImageInfo imageInfo = buildImage(imageFile, fileName,null,imageFileName,Constants.zhengshuFlag); 
			imageInfoManager.save(imageInfo);
			logger.debug("Id:"+imageInfo.getId()+"=======suffix:"+imageInfo.getSuffix());
			
			writeImg(imageInfo, Constants.zhengshuFlag);
			
			painting.setZhengshu(imageInfo);
		}
	}
	
	/**
	 * 处理作品的其他三幅作品
	 */
	private void dealOtherPicturesOfPainting(Painting painting){
		String imageTypeFlag = null;
		if( painting.getCatalogType() != null){
			CatalogType catalogType = catalogTypeManager.get(painting.getCatalogType().getId());
			imageTypeFlag = catalogType.getEnglish_name();
		}
		String picImage2 = request.getParameter("back_image2");
		if( picImage2 != null && !"".equals(picImage2)){
			String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + picImage2; //图片物理路径
			File file = new File(imageFilePath);
			ImageInfo imageInfo = saveImageToDB(file, picImage2, null,picImage2,imageTypeFlag);
			painting.setImageInfo2(imageInfo);
		}
		
		String picImage3 = request.getParameter("back_image3");
		if( picImage3!= null && !"".equals(picImage3)){
			String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + picImage3; //图片物理路径
			File file = new File(imageFilePath);
			ImageInfo imageInfo = saveImageToDB(file, picImage3, null,picImage3,imageTypeFlag);
			painting.setImageInfo3(imageInfo);
		}
		
		String picImage4 = request.getParameter("back_image4");
		if( picImage4!= null && !"".equals(picImage4)){
			String imageFilePath = getImageUploadPath()+CommonsUtil.getPathSymbol() + picImage4; //图片物理路径
			File file = new File(imageFilePath);
			ImageInfo imageInfo = saveImageToDB(file, picImage4, null,picImage4,imageTypeFlag);
			painting.setImageInfo4(imageInfo);
		}
		
		ImageInfo imageInfo = painting.getImageInfo();
		if( imageInfo != null){
			imageInfo = imageInfoManager.get(imageInfo.getId());
			imageInfo.setMemo(imageTypeFlag);
			imageInfoManager.save(imageInfo);
		}
	}
	
	/**
	 *@Todo:保存图片至DB
	 * @param file 图片文件
	 * @param originalName  图片原始名字
	 * @param sharpId 图片形状类型 15表示专题背景图片
	 */
	public ImageInfo saveImageToDB(File file,String originalName,String sharpId,String newNameUploaded,String memo){
		ImageInfo imageInfo = buildImage(file,originalName,sharpId,newNameUploaded,memo);
    	imageInfoManager.save(imageInfo);
    	return imageInfo;
	}
	
	/**
	* @Description: 更改排序
	 */
	public String changeSequence(){
		String data = request.getParameter("data");
		if( data!= null && !data.equals("")){
			String[] arr = data.split("\\}\\,\\{");
			for (int i = 0; i < arr.length; i++) {
				String item = arr[i].replace("{", "").replace("}", "");
				String[] objArray = item.split(",");
				String idStr = objArray[0];
				String numberStr = objArray[1];
				
				Painting painting = paintingManager.get(Long.valueOf(idStr));
				
				painting.setOrderNo(Integer.valueOf(numberStr));
				paintingManager.save(painting);
			}
		}
		
		request.setAttribute("ajaxData", "0000");
		return "changeSequence";
	}
	
	/**
	* @Description: 列出某画家所有作品便于排序
	 */
	public String listAllPaintingsOfPainter(){
		
		String painter_id_str = request.getParameter("painter_Id");
		Long painterId = Long.parseLong(painter_id_str);
		
		Painter painter = painterManager.get(painterId);
		List<Painting> paintingList = paintingManager.findPaintingsByPainter(painterId);
		
		request.setAttribute("paintingList", paintingList);
		request.setAttribute("painter", painter);
		
		return "listAllPaintingsOfPainter";
	}
	
	private void generateImageOfPaintingAfterSaved(Painting painting) throws Exception{
		if(painting.getImageInfo() != null){
			ImageInfo img = imageInfoManager.get(painting.getImageInfo().getId());
			generateImageOfPaintingFirstTime(painting,img);
		}
		if(painting.getImageInfo2() != null){
			ImageInfo img = imageInfoManager.get(painting.getImageInfo2().getId());
			generateImageOfPaintingFirstTime(painting,img);
		}
		if(painting.getImageInfo3() != null){
			ImageInfo img = imageInfoManager.get(painting.getImageInfo3().getId());
			generateImageOfPaintingFirstTime(painting,img);
		}
		if(painting.getImageInfo4() != null){
			ImageInfo img = imageInfoManager.get(painting.getImageInfo4().getId());
			generateImageOfPaintingFirstTime(painting,img);
		}
	}

    public void setMyFileFileName(String fileName)  {
        this.fileName = fileName;
    }
       
    public String getFileName() {
		return fileName;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile)  {
        this.myFile = myFile;
    } 
	
	public void setBidManager(BidManager bidManager) {
		this.bidManager = bidManager;
	}
	
}
